package org.lds.hotkey.worker.component;

import lombok.extern.slf4j.Slf4j;
import org.lds.hotkey.common.model.dto.ResultDTO;
import org.lds.hotkey.common.util.AssertUtil;
import org.lds.hotkey.common.util.InetAddressUtil;
import org.lds.hotkey.common.util.ScheduledUtil;
import org.lds.hotkey.console.remote.ConsoleClient;
import org.lds.hotkey.console.remote.model.request.WorkerRegisterRequest;
import org.lds.hotkey.worker.common.enums.WorkerErrorEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.net.InetAddress;

@Slf4j
@Component
public class WorkerRegisterRunner implements ApplicationRunner {

    @Value("${hotkey.worker.app-name}")
    private String appName;

    @Value("${server.port}")
    private int port;

    @Autowired
    private ConsoleClient consoleClient;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        ScheduledUtil.defaultClosableScheduled(() -> execute());
    }

    private void execute() {
        InetAddress address = InetAddressUtil.getInetAddress();
        // worker注册
        ResultDTO resultDTO = consoleClient.registerWorker(WorkerRegisterRequest.builder()
                .appName(appName)
                .name(address.getHostName())
                .ip(address.getHostAddress())
                .port(port)
                .build());
        AssertUtil.assertTrue(ResultDTO.isSuccess(resultDTO), WorkerErrorEnum.WORKER_REGISTER_FAIL);
        log.info("Worker注册成功");
    }
}
